﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Rail.Commons.HardInfo
{
    public class HardWareInformation
    {

        private static string macAddress=string.Empty;
        /// <summary>
        /// Mac地址
        /// </summary>
        public static string MacAddress
        {
            get
            {
                if (!string.IsNullOrEmpty(macAddress))
                    return macAddress;
                NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface ni in interfaces)
                {
                    var pMac = ni.GetPhysicalAddress();
                    if (pMac != null && !string.IsNullOrEmpty(pMac.ToString()))
                    {
                        //Console.WriteLine("MAC : " + ni.GetPhysicalAddress().ToString());
                        macAddress = pMac.ToString();
                        break;
                    }
                }
                return macAddress;
            }
        }

        private static string cpuInfo = string.Empty;
        static object lockobj = new object();
        /// <summary>
        /// CPU信息
        /// </summary>
        public static string CPUInfo
        {
            get
            {
                lock (lockobj)
                {
                    if (!string.IsNullOrEmpty(cpuInfo))
                        return cpuInfo;
                    ManagementClass cimobject = new ManagementClass("Win32_Processor");
                    ManagementObjectCollection moc = cimobject.GetInstances();
                    foreach (ManagementObject mo in moc)
                    {
                        if (mo.Properties["ProcessorId"] == null || mo.Properties["ProcessorId"].Value == null) continue;
                        cpuInfo += mo.Properties["ProcessorId"].Value.ToString();
                        if (!string.IsNullOrEmpty(cpuInfo)) break;
                    }
                    return cpuInfo;
                }
            }
        }


        private static string diskNo = string.Empty;
        /// <summary>
        /// 硬盘序列号
        /// </summary>
        public static string DiskNo
        {
            get
            {
                if (!string.IsNullOrEmpty(diskNo))
                    return diskNo;
                /*
                ManagementClass cimobjectHDid = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection mocHDid = cimobjectHDid.GetInstances();
                foreach (ManagementObject mo in mocHDid)
                {
                    diskNo = (string)mo.Properties["Model"].Value;
                    return diskNo;
                }
                return diskNo;
                */

                diskNo = GetSystemDiskNo();
                return diskNo;
            }
        }

        //获取系统所在硬盘的序列号
        private static string GetSystemDiskNo()
        {
            ManagementClass cimObject = new ManagementClass("Win32_PhysicalMedia");
            ManagementObjectCollection moc = cimObject.GetInstances();
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (ManagementObject mo in moc)
            {
                string tag = mo.Properties["Tag"].Value.ToString().ToLower().Trim();
                string hdId = (string)mo.Properties["SerialNumber"].Value ?? string.Empty;
                hdId = hdId.Trim();
                dict.Add(tag, hdId);
            }
            cimObject = new ManagementClass("Win32_OperatingSystem");
            moc = cimObject.GetInstances();
            string currentSysRunDisk = string.Empty;
            foreach (ManagementObject mo in moc)
            {
                currentSysRunDisk = Regex.Match(mo.Properties["Name"].Value.ToString().ToLower(), @"harddisk\d+").Value;
            }
            var results = dict.Where(x => Regex.IsMatch(x.Key, @"physicaldrive" + Regex.Match(currentSysRunDisk, @"\d+$").Value));
            if (results.Any()) return results.ElementAt(0).Value;
            return "";
        }

        public static string GetMachineCode()
        {
            string machineCode = "";
            MD5CryptoServiceProvider provider1;
            byte[] array1;
            string text1;
            string text2;
            byte num1;
            byte[] array2;
            int num2;
            provider1 = new MD5CryptoServiceProvider();
            string cpuInfo = "";//CPU 序列号
            ManagementClass cimobject = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                cpuInfo += mo.Properties["ProcessorId"].Value.ToString();
            }
            //获取硬盘ID

            //获取网卡硬件地址
            string strMac = "";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection mocMac = mc.GetInstances();
            foreach (ManagementObject mo in mocMac)
            {
                if ((bool)mo["IPEnabled"] == true)
                    strMac += mo["MacAddress"].ToString();
                mo.Dispose();
            }

            array1 = provider1.ComputeHash(Encoding.Default.GetBytes(cpuInfo + strMac));
            text1 = "ENTOPYMICROSYSTEMSDEVINIMMUHENDISLIK231456789ACD23456789AEFABGHJKLMNPRSTUVWYZXAHMETALIAKKASHAKANESKICI";
            text2 = string.Empty;
            array2 = array1;
            for (num2 = 0; (num2 < array2.Length); num2 = (num2 + 1))
            {
                num1 = array2[num2];
                text2 = string.Concat(text2, text1.Substring((num1 % text1.Length), 1));
            }
            machineCode = text2.Substring(0, 10);
            return machineCode;
            //return cpuInfo + HDid + strMac;
        }
    }
}